﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using AL.Doodled.Extensions.MemberInfo;
using System.Reflection;

namespace AL.Doodled.Extensions.Object
{
    #region enum
    public enum Access
    {
        All,
        Default
    }
    #endregion

    /// <summary>
    /// This class only contains extension methods for the object class.
    /// </summary>
    public static class ObjectExtensionMethods
    {
        public static string ALFormat(this object obj,
                                      string str,
                                      Access access = Access.Default)
        {
            Type objType = obj.GetType();
            string output = str;

            foreach (Match match in Regex.Matches(str, @"\$([^$]*)"))
            {
                string full = match.Groups[0].Value;
                string s = (match.Groups[1] ?? match.Groups[0]).Value;
                if (objType.GetMember(s, defineAccess(access)).Length > 0)
                    output = output.Replace(full + "$", objType.GetMember(s,
                        defineAccess(access))[0].GetValue(obj).ToString());
            }

            return output;
        }

        private static BindingFlags defineAccess(Access accessLevel)
        {
            BindingFlags def = BindingFlags.Public | BindingFlags.Static |
                BindingFlags.Instance;
            if (accessLevel == Access.Default)
                return def;
            else
                return def | BindingFlags.NonPublic;
        }
    }
}
